﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Dracham.Classes
{
    public class SpawnTimer : GameTimer
    {
        public Position Position { get; set; }
        public Object Object { get; set; }
        public ObjectType ObjectType { get; set; }
        public Int32 ObjectId { get; set; }

        public override void Run()
        {
            GameWorld.Timers.RemoveTimer(this);

            switch (this.ObjectType)
            {
                case ObjectType.Creature:
                    this.Object = GameWorld.CreaturePool.SingleOrDefault(c => c.CreatureId == this.ObjectId);
                    this.Object.Position = this.Position;
                    (this.Object as Creature).Initialize();
                    break;
                case ObjectType.NPC:
                    break;
            }

            this.Object.OnObjectExpire += new Object.ObjectExpiredDelegate(this.Queue);
            this.Position.Zone.Objects.Add(this.Object);
        }

        public SpawnTimer()
        {
            GameWorld.Spawns.Add(this);
        }

        public static SpawnTimer FromXmlNode(XmlNode node, Position pos)
        {
            if (node == null || pos == null)
                return null;

            SpawnTimer s = new SpawnTimer();
            s.Position = pos;

            s.Interval = Convert.ToDouble(node.Attributes["Interval"].Value);
            s.ObjectType = (ObjectType)Enum.Parse(typeof(ObjectType), node.Attributes["Type"].Value);
            s.ObjectId = Convert.ToInt32(node.Attributes["Id"].Value);

            return s;
        }

        public void Queue()
        {
            Console.WriteLine("Requeue");

            if (this.Object != null)
            {
                if (!this.Object.HasExpired) return;

                this.Object = null;
            }

            if (this.Interval >= 0)
            {
                this.LastRun = DateTime.Now;
                GameWorld.Timers.AddTimer(this);
            }
        }
    }
}
